package gw.com.android.ui.positions;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.gwtsz.android.rxbus.RxBus;
import com.gwtsz.gts2.hx.R;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import gw.com.android.app.ActivityManager;
import gw.com.android.app.AppContances;
import gw.com.android.app.AppMain;
import gw.com.android.model.ConfigType;
import gw.com.android.model.ConfigUtil;
import gw.com.android.model.DataManager;
import gw.com.android.terminal.AppTerminal;
import gw.com.android.terminal.GTSDataListener;
import gw.com.android.ui.MainActivity;
import gw.com.android.ui.dialog.PopupConfirmDialog;
import gw.com.android.ui.dialog.PopupDoubleBtnDialog;
import gw.com.android.ui.quote2.NewQuoteFragment;
import gw.com.android.ui.trade.TradeBusiness;
import gw.com.android.utils.ColorThemeUtil;
import gw.com.android.utils.ServerConnnectUtil;
import gw.com.jni.library.terminal.GTSConst;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import www.com.library.app.Logger;
import www.com.library.model.DataItemDetail;
import www.com.library.model.DataItemResult;
import www.com.library.util.CommonUtils;
import www.com.library.util.NetworkMonitor;
import www.com.library.util.StringFormatter;
import www.com.library.view.BtnClickListener;

/**
 * Created by reeta.zou on 2016/7/7.
 * 挂单适配器
 */
public class PendingAdapter extends RecylerListAdapter {

    private DataItemResult mList;
    /**
     * 展开项id
     */
    private int mExpandOrderId = -1;

    /**
     * 正在撤单中的订单id
     */
    private int mOrder = 0;

    public Disposable rxBusRegister;

    /**
     * 初始化界面数据
     *
     * @param context
     */
    public PendingAdapter(Context context, RecyclerView mView) {
        super(context, mView);
        mList = new DataItemResult();
        mList.appendItems(DataManager.instance().getSortOrderList(DataManager.instance().mOrderInfoList));
        notifyDataChanged();
    }

    @Override
    public void refreshData() {
        mList.clear();
        mList.appendItems(DataManager.instance().getSortOrderList(DataManager.instance().mOrderInfoList));
        notifyDataChanged();
    }

    @Override
    public void refreshPrice(int codeId) {
        super.refreshPrice(codeId);
        if (!mIsRefreshing) {
            int count = mList.getDataCount();
            for (int i = 0; i < count; i++) {
                if (mList.getItem(i).getInt(GTSConst.JSON_KEY_CODEID) == codeId) {
                    notifyItemChanged(i, mList.getItem(i));
                }
            }
        }
    }

    @Override
    public void refreshOrder(int orderId) {
        super.refreshOrder(orderId);
        if (!mIsRefreshing) {
            int count = mList.getDataCount();
            for (int i = 0; i < count; i++) {
                if (mList.getItem(i).getInt(GTSConst.JSON_KEY_ID) == orderId) {
                    notifyItemChanged(i, mList.getItem(i));
                    break;
                }
            }
        }

    }

    public int getItemCount() {
        if (null != mList) {
            return mList.getDataCount();
        }
        return 0;
    }

    public DataItemDetail getItem(int position) {
        if (position < 0 || position >= mList.getDataCount()) {
            return null;
        }

        if (null != mList && null != mList.getItem(position)) {
            return mList.getItem(position);
        }

        return null;
    }

    @Override
    public void updateViews(RecyclerView.ViewHolder viewholder, int position) {
        DataItemDetail mItem = getItem(position);
//        mItem.printString();
        ListItemView mItemView = (ListItemView) viewholder;
        if (mExpandOrderId == mItem.getInt(GTSConst.JSON_KEY_ID)) {
            mItemView.btnLayout.setVisibility(View.VISIBLE);
        } else {
            mItemView.btnLayout.setVisibility(View.GONE);
        }
        // 为按钮添加相关tag值，方便后续点击事件调用参数
        mItemView.itemView.setTag(position);
        if (null != mItem) {
            mItemView.prdnameV.setText(DataManager.instance().getPrdName(mItem));
            mItemView.timeV.setText(StringFormatter.instance().secToDateTime(mItem.getInt(GTSConst.JSON_KEY_TIME)));

            // 买卖类型和手数
            m_spannableTitle.reset();

            if (mItem.getInt(GTSConst.JSON_KEY_DIRECTION) == AppContances.TRADE_TYPE_BUY) {
                m_spannableTitle.append(AppMain.getAppString(R.string.order_trade_buy_lot, mItem.getString(GTSConst.JSON_KEY_VOLUME)));
            } else {
                m_spannableTitle.append(AppMain.getAppString(R.string.order_trade_sell_lot, mItem.getString(GTSConst.JSON_KEY_VOLUME)));
            }

            mItemView.dirV.setText(m_spannableTitle.getBuilder());
            mItemView.orderIdV.setText("#" + String.valueOf(mItem.getInt(GTSConst.JSON_KEY_ID)));

            if (mItem.getInt(GTSConst.JSON_KEY_EXPIRETYPE) == AppContances.VALID_TYPE_DAY) {
                mItemView.expireView.setText(AppMain.getAppString(R.string.order_item_trade_expiry_day));
            } else {
                mItemView.expireView.setText(AppMain.getAppString(R.string.order_item_trade_expiry_week));
            }

            if (mItem.getString(GTSConst.JSON_KEY_STOPLOSS) != null && mItem.getString(GTSConst.JSON_KEY_STOPLOSS).length() > 0 && !mItem.getString(GTSConst.JSON_KEY_STOPLOSS).equals("0")) {
                mItemView.lossV.setText(AppMain.getAppString(R.string.order_item_title_loss) + mItem.getString(GTSConst.JSON_KEY_STOPLOSS));
                mItemView.lossV.setVisibility(View.VISIBLE);
            } else {
                mItemView.lossV.setText(AppMain.getAppString(R.string.order_item_title_loss) + 0);
                mItemView.lossV.setVisibility(View.VISIBLE);
            }
            if (mItem.getString(GTSConst.JSON_KEY_STOPPROFIT) != null && mItem.getString(GTSConst.JSON_KEY_STOPPROFIT).length() > 0 && !mItem.getString(GTSConst.JSON_KEY_STOPPROFIT).equals("0")) {
                mItemView.winV.setText(AppMain.getAppString(R.string.order_item_title_profit) + mItem.getString(GTSConst.JSON_KEY_STOPPROFIT));
                mItemView.winV.setVisibility(View.VISIBLE);
            } else {
                mItemView.winV.setText(AppMain.getAppString(R.string.order_item_title_profit) + 0);
                mItemView.winV.setVisibility(View.VISIBLE);
            }

            updateViews(mItemView, mItem);
        }
    }

    @Override
    public void updateViews(RecyclerView.ViewHolder holder, List payloads) {
        DataItemDetail item = (DataItemDetail) payloads.get(0);
        ListItemView mItemView = (ListItemView) holder;
        if (null != item) {
            updateViews(mItemView, item);
        }
    }

    /**
     * 刷新界面
     *
     * @param mItemView
     */
    private synchronized void updateViews(ListItemView mItemView, DataItemDetail mItem) {
        // 开仓价
        m_spannableTitle.reset();
        m_spannableTitle.setForegroundColorSpanString(AppMain.getAppString(R.string.order_item_title_price), ColorThemeUtil.instance().color_c);
        if (mItem.getInt(GTSConst.JSON_KEY_ORDERPRICESTATE) != 0) {
            m_spannableTitle.setBackgroundColorSpanString(
                    mItem.getString(GTSConst.JSON_KEY_ORDERPRICE), ColorThemeUtil.instance().color_t);
        } else {
            m_spannableTitle.setBackgroundColorSpanString(
                    mItem.getString(GTSConst.JSON_KEY_ORDERPRICE), ColorThemeUtil.instance().transparent);
        }
        mItemView.donePrice.setText(m_spannableTitle.getBuilder());
//        DataItemDetail tickItem = DataManager.instance().getTickModel(mItem.getInt(GTSConst.JSON_KEY_CODEID));
//        if(null != tickItem){
//            setClosePriceColor(mItemView.closePrice, tickItem, mItem.getInt(GTSConst.JSON_KEY_DIRECTION));
//        }else{
//            setClosePriceColor(mItemView.closePrice, mItem, mItem.getInt(GTSConst.JSON_KEY_DIRECTION));
//        }
        setClosePriceColor(mItemView.closePrice, mItem, mItem.getInt(GTSConst.JSON_KEY_DIRECTION));
    }

    /**
     * 判断颜色方向
     *
     * @return
     */
    public void setClosePriceColor(TextView priceView, DataItemDetail mItem, int direction) {
        if (direction == AppContances.TRADE_TYPE_BUY) {
            priceView.setText(mItem.getString(GTSConst.JSON_KEY_BUYPRICE));
            ColorThemeUtil.instance().setPriceColor(priceView, mItem.getInt(GTSConst.JSON_KEY_BUYPRICESTATE), mItem.getInt(GTSConst.JSON_KEY_BUYPRICEARRAW), true);
        } else {
            priceView.setText(mItem.getString(GTSConst.JSON_KEY_SELLPRICE));
            ColorThemeUtil.instance().setPriceColor(priceView, mItem.getInt(GTSConst.JSON_KEY_SELLPRICESTATE), mItem.getInt(GTSConst.JSON_KEY_SELLPRICEARRAW), true);
        }
    }

    @Override
    public int getLayoutID() {
        return R.layout.list_item_pending;
    }

    @Override
    public RecyclerView.ViewHolder getViewHolder(View v, int type) {
        return new ListItemView(v);
    }

    public class ListItemView extends RecyclerView.ViewHolder {
        /**
         * 产品名称
         */
        @BindView(R.id.trade_prd_name)
        public TextView prdnameV;
        /**
         * 买卖方向
         */
        @BindView(R.id.trade_type)
        public TextView dirV;
        /**
         * 开仓价
         */
        @BindView(R.id.trade_open_price)
        public TextView donePrice;
        /**
         * 有效期
         */
        @BindView(R.id.trade_order_expiry)
        public TextView expireView;
        /**
         * 时间
         */
        @BindView(R.id.trade_time)
        public TextView timeV;
        /**
         * 平仓价
         */
        @BindView(R.id.trade_profit)
        public TextView closePrice;
        /**
         * 止损
         */
        @BindView(R.id.trade_open_loss)
        public TextView lossV;
        /**
         * 止盈
         */
        @BindView(R.id.trade_open_win)
        public TextView winV;
        /**
         * 订单号
         */
        @BindView(R.id.trade_order_id)
        public TextView orderIdV;
        @BindView(R.id.rl_content)
        public View content;
        /**
         * 按钮布局
         */
        @BindView(R.id.btn_layout)
        public View btnLayout;

        public ListItemView(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }

        @OnClick(R.id.content_layout)
        void onClickContent() {
            if (CommonUtils.isFastDoubleClick()) {
                return;
            }
            final int positionKey = (int) itemView.getTag();
            DataItemDetail mItem = getItem(positionKey);
            Logger.i("content_layout按钮点击了");
            isClick = true;
            if (mItem == null) return;//这里修复一个可能的bug，因为挂单，有可能被交易成功，这里得到的mItem也有可能变成null（因为list变化了），所以必须做空指针判定
            if (mExpandOrderId == mItem.getInt(GTSConst.JSON_KEY_ID)) {
                mExpandOrderId = -1;
            } else {
                mExpandOrderId = mItem.getInt(GTSConst.JSON_KEY_ID);
            }
            Logger.i("expandOrderId = " + mExpandOrderId);
            notifyDataSetChanged();
            if (null != mListV) {
                mListV.post(new Runnable() {
                    @Override
                    public void run() {
                        mListV.smoothScrollToPosition(positionKey);
                    }
                });
            }
        }

        @OnClick(R.id.cancel_btn)
        void onCancelOrder() {
            if (CommonUtils.isFastDoubleClick()) {
                return;
            }
            final int positionKey = (int) itemView.getTag();
            final DataItemDetail mItem = getItem(positionKey);
            Logger.i("cancel_btn按钮点击了");

            if (mOrder == mItem.getInt(GTSConst.JSON_KEY_ID)) {
                final PopupConfirmDialog dialog = PopupConfirmDialog.newInstance(mOwnerAct, "", ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1054));
                dialog.show();
                return;
            }

            if (!checkTradable(mItem, false)) {
                return;
            }

            String title = "#" + mItem.getInt(GTSConst.JSON_KEY_ID) + AppMain.getAppString(R.string.order_btn_title_cancel);
            PopupDoubleBtnDialog dialog = PopupDoubleBtnDialog.newInstance((Activity) mOwnerAct, title, ConfigUtil.instance().getErrorConfigObject().optString(ConfigType.SERVER_ERROR_1030),
                    new BtnClickListener() {

                        @Override
                        public void onBtnClick(int viewID) {
                            if (viewID == R.id.action_btn_pos) {
                                // 未连上网络时,气泡提示
                                if (!NetworkMonitor.hasNetWork()) {
                                    mOrder = 0;
                                    return;
                                }
                                new Timer().schedule(new TimerTask() {//设置 20秒内服务器没有回包

                                    @Override
                                    public void run() {
                                        mOrder = 0;
                                        if (null != rxBusRegister && rxBusRegister.isDisposed()) {
                                            rxBusRegister.dispose();
                                            rxBusRegister = null;
                                        }
                                    }
                                }, AppContances.TIMER_ORDER_TASK_TIME);
                                mOrder = mItem.getInt(GTSConst.JSON_KEY_ID);
                                int mSeq = GTSDataListener.curSeq++;
                                GTSDataListener.instance().addSeqList(mSeq + "", AppContances.ORDER_TYPE_ORDER_CANCEL + "");
                                rxBusRegister = RxBus.getInstance().register(GTSConst.REPLY_ORDER_CANCEL + "", Bundle.class).observeOn(AndroidSchedulers.mainThread())
                                        .subscribe(new Consumer<Bundle>() {

                                            @Override
                                            public void accept(@NonNull Bundle bundle) throws Exception {
                                                if (null != bundle) {
                                                    int result = bundle.getInt("iValue");
                                                    if (result == 0) {
                                                        Logger.i("onServerResponse 撤单成功通知  " + " iValue = " + result);
                                                        mOrder = 0;
                                                        // 发送自选股请求
                                                        AppTerminal.instance().sendQuoteSubscribe(DataManager.instance().getQuoteSubscribeCode(0));
                                                    } else {
                                                        Logger.i("onServerResponse 撤单失败通知 " + " iValue = " + result);
                                                        mOrder = 0;
                                                        mOwnerAct.showToastPopWindow(ConfigUtil.instance().getErrorConfigObject().optString(result + ""));
                                                    }
                                                    if (null != rxBusRegister && rxBusRegister.isDisposed()) {
                                                        rxBusRegister.dispose();
                                                        rxBusRegister = null;
                                                    }
                                                }
                                            }
                                        });
                                AppTerminal.instance().reqOrderCancel(mItem.getInt(GTSConst.JSON_KEY_ID), mSeq);
                            }
                        }
                    });
            dialog.show();
        }

        @OnClick(R.id.modify_btn)
        void onModityOrder() {
            if (CommonUtils.isFastDoubleClick()) {
                return;
            }
            final int positionKey = (int) itemView.getTag();
            DataItemDetail mItem = getItem(positionKey);
            Logger.i("modify_btn按钮点击了");

            if (!checkTradable(mItem, true)) {
                return;
            }
            ActivityManager.showPendingOrderModifyActivity(mOwnerAct, mItem);
        }

        @OnClick(R.id.chart_btn)
        void onChartView() {
            if (CommonUtils.isFastDoubleClick()) {
                return;
            }
            final int positionKey = (int) itemView.getTag();
            DataItemDetail mItem = getItem(positionKey);
            Logger.i("chart_btn按钮点击了");
            if (!NetworkMonitor.hasNetWork()) {
                return;
            }
            if (!ServerConnnectUtil.instance().isTradeConnect || !ServerConnnectUtil.instance().isQuoteConnect) {
                ServerConnnectUtil.instance().reConnectServerConfirm(mOwnerAct);
                return;
            }
            if (null == mItem) {
                Logger.i("挂单数据对象为空！！！");
                showErrorMsg(ConfigType.SERVER_ERROR_1021);
                return;
            }
            if (mOwnerAct instanceof MainActivity) {
                RxBus.getInstance().post(NewQuoteFragment.CHANGE_QUOTE_EVENT, mItem.getInt(GTSConst.JSON_KEY_CODEID));
//                ((MainActivity) mOwnerAct).setTabFragment(ConfigType.TAB_QUOTE_TAG, "");
                ActivityManager.showChartActivity(mOwnerAct, mItem.getInt(GTSConst.JSON_KEY_CODEID), mItem.getInt(GTSConst.JSON_KEY_ZONE), AppContances.TRADE_TYPE_FORM_QUOTE);

            }
        }
    }

    /**
     * 下单判断
     *
     * @return
     */
    private boolean checkTradable(DataItemDetail mModel, boolean isOpenOrder) {
        if (!NetworkMonitor.hasNetWork()) {
            return false;
        }
        if (null == mModel) {
            Logger.i("挂单数据对象为空！！！");
            showErrorMsg(ConfigType.SERVER_ERROR_1021);
            return false;
        }

        if (!TradeBusiness.PreOrderCheck(mOwnerAct, mModel.getInt(GTSConst.JSON_KEY_ZONE), mModel.getInt(GTSConst.JSON_KEY_TRADESTATE), isOpenOrder)) {
            return false;
        }

        return true;
    }

    private void showErrorMsg(String errorId) {
        final PopupConfirmDialog dialog = PopupConfirmDialog.newInstance(mOwnerAct, "", ConfigUtil.instance().getErrorConfigObject().optString(errorId));
        dialog.show();
    }

}
